package com.labofjet.util;

import java.util.Set;

import com.labofjet.bean.impl.ValidationResult;

import javax.validation.ConstraintViolation;
import javax.validation.Validator;

import org.apache.commons.lang3.StringUtils;

/**
 * 目的是为了结合javax下的验证规范,提供一些简单的校验对象属性的方法
 * 
 * @author jyzjyz12@163.com
 * 
 */
public class ValidationUtils {
    private static Validator validator = SpringContextUtils.getBean(Validator.class);

    private ValidationUtils() {

    }

    /**
     * 验证单个对象,不会返回null
     * 
     * @param target
     * @return
     */
    public static <T> ValidationResult validateObj(T target, Class<?>... groups) {
        ValidationResult vr = new ValidationResult();
        Set<ConstraintViolation<T>> violationsSet = validator.validate(target, groups);
        for (ConstraintViolation<T> violation : violationsSet) {
            if (StringUtils.isNotEmpty(violation.getPropertyPath().toString())) {
                vr.putFieldViolationsInfo(violation.getPropertyPath().toString(), violation.getMessage());
            } else {
                vr.addViolationsInfo(violation.getMessage());
            }
        }
        return vr;
    }
}
